package com.kasax.httpsupport;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class HttpCall implements Call {
    CatHttpClient.Config config;
    Request request;

    private IRequestHandler requestHandler = new RequestHandler();

    public HttpCall(CatHttpClient.Config config, Request request) {
        this.config = config;
        this.request = request;
    }

    @Override
    public Response execute() {
        SyncTask syncTask = new SyncTask();
        Response response;
        try {
            response = HttpExecutor.getInstance().submit(syncTask);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Response.Builder().code(400).message("线程异常中断").body(new ResponseBody(null)).build();
    }

    @Override
    public void enqueue(Callback callback) {
        Runnable httpTask = new HttpTask(this, callback, requestHandler);
        HttpExecutor.getInstance().enqueue(new FutureTask<>(httpTask, null));
    }

    /**
     * 同步提交Callable
     */
    class SyncTask implements Callable<Response> {

        @Override
        public Response call() throws Exception {
            Response response = requestHandler.handlerRequest(HttpCall.this);
            return response;
        }
    }
}
